package com.example.mystore.servlets.service;

import com.example.mystore.dao.CategoryDao;
import com.example.mystore.dao.CommoditiesDao;
import com.example.mystore.entity.Commodity;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class DisplayServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp){
        int getCommodity = 1;
        if (req.getParameter("category") != null){
            getCommodity = Integer.parseInt(req.getParameter("category"));
        }
        HashMap<Integer, ArrayList<Commodity>> commodityHM;
        //获取商品以及分类，提供服务端使用，不用反复读取数据库
        if (getServletContext().getAttribute("commodityHM") == null){
            commodityHM = CommoditiesDao.selectAll1();
            getServletContext().setAttribute("commodityHM",commodityHM);
        }else {
            commodityHM = (HashMap<Integer, ArrayList<Commodity>>) getServletContext().getAttribute("commodityHM");
        }
        //获取商品分类存入Session域中
        if(req.getSession().getAttribute("categoryHM") == null){
            HashMap<Integer,String> categoryHM = CategoryDao.selectCategory();
            req.getSession().setAttribute("categoryHM",categoryHM);
        }
        ArrayList<Commodity> commodityArr = commodityHM.get(getCommodity);
        req.getSession().setAttribute("commodityArr",commodityArr);
        try {
            req.getRequestDispatcher("/display.jsp").forward(req,resp);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }
    public void doPost(HttpServletRequest req, HttpServletResponse resp) {
        doGet(req,resp);
    }

}
